package org.solar.wechat;

import java.awt.EventQueue;
import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.swing.UIManager;

import com.blade.kit.json.JSONArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.blade.kit.DateKit;
import com.blade.kit.StringKit;
import com.blade.kit.http.HttpRequest;
import com.blade.kit.json.JSONObject;

import org.solar.wechat.exception.WechatException;
import org.solar.wechat.listener.WechatListener;
import org.solar.wechat.model.WechatContact;
import org.solar.wechat.model.WechatMeta;
import org.solar.wechat.service.WechatService;
import org.solar.wechat.service.WechatServiceImpl;
import org.solar.wechat.ui.QRCodeFrame;
import org.solar.wechat.util.CookieUtil;
import org.solar.wechat.util.Matchers;

/**
 * Hello world!
 */
public class WechatClient {

	private static final Logger LOGGER = LoggerFactory.getLogger(WechatClient.class);

	private int tip = 0;
	private WechatListener wechatListener = new WechatListener();
	private WechatService wechatService = new WechatServiceImpl();
	private WechatMeta wechatMeta = new WechatMeta();
	private WechatContact wechatContact;
	private Map<String, String> userNameMap = new HashMap();
	private QRCodeFrame qrCodeFrame;
	
	public WechatClient() {
		System.setProperty("https.protocols", "TLSv1");
		System.setProperty("jsse.enableSNIExtension", "false");
	}

	/**
	 * getUUID
	 * https://login.weixin.qq.com/l/4dQEfDmbyw==
	 * https://login.weixin.qq.com/l/uuid
	 * @return
	 */
	public String getUUID() throws WechatException {
		String uuid = wechatService.getUUID();
		wechatMeta.setUuid(uuid);
		 return uuid;
	}


	/**
	 * 显示二维码
	 * https://login.weixin.qq.com/l/4dQEfDmbyw==
	 * https://login.weixin.qq.com/l/uuid
	 * @return
	 */
	public void showQrCode() throws WechatException {
		String uuid = wechatService.getUUID();
		wechatMeta.setUuid(uuid);

		LOGGER.info("获取到uuid为 [{}]", uuid);
		String url = Config.QRCODE_URL + uuid;
		final File output = new File("temp.jpg");
		HttpRequest.post(url, true, "t", "webwx", "_", DateKit.getCurrentUnixTime()).receive(output);
		
		
		if (null != output && output.exists() && output.isFile()) {
			EventQueue.invokeLater(new Runnable() {
				public void run() {
					try {
						UIManager.setLookAndFeel("com.sun.java.swing.plaf.nimbus.NimbusLookAndFeel");
						qrCodeFrame = new QRCodeFrame(output.getPath());
					} catch (Exception e) {
						e.printStackTrace();
					}
				}
			});
		}
	}

	/**
	 * 等待登录
	 */
	public String waitForLogin() throws WechatException {
		this.tip = 1;
		String url = "https://login.weixin.qq.com/cgi-bin/mmwebwx-bin/login";
		HttpRequest request = HttpRequest.get(url, true, "tip", this.tip, "uuid", wechatMeta.getUuid(), "_",
				DateKit.getCurrentUnixTime());

		LOGGER.info("等待登录...");
		LOGGER.debug("" + request.toString());

		String res = request.body();
		request.disconnect();

		if (null == res) {
			throw new WechatException("扫描二维码验证失败");
		}
		String code = Matchers.match("window.code=(\\d+);", res);
		if (null == code) {
			throw new WechatException("扫描二维码验证失败");
		} else {
			if (code.equals("201")) {
				LOGGER.info("成功扫描,请在手机上点击确认以登录");
				tip = 0;
			} else if (code.equals("200")) {
				LOGGER.info("正在登录...");
				String pm = Matchers.match("window.redirect_uri=\"(\\S+?)\";", res);
				String redirect_uri = pm + "&fun=new";
				wechatMeta.setRedirect_uri(redirect_uri);
				
				String base_uri = redirect_uri.substring(0, redirect_uri.lastIndexOf("/"));
				wechatMeta.setBase_uri(base_uri);
				
				LOGGER.debug("redirect_uri={}", redirect_uri);
				LOGGER.debug("base_uri={}", base_uri);
			} else if (code.equals("408")) {
				throw new WechatException("登录超时");
			} else {
				LOGGER.info("扫描code={}", code);
			}
		}
		return code;
	}
	
	public void closeQrWindow() {
		qrCodeFrame.dispose();
	}

	/**
	 * 登录
	 */
	public void login() throws WechatException {
		HttpRequest request = HttpRequest.get(wechatMeta.getRedirect_uri());
		
		LOGGER.debug("" + request);
		String res = request.body();
		wechatMeta.setCookie(CookieUtil.getCookie(request));
		request.disconnect();

		if (StringKit.isBlank(res)) {
			throw new WechatException("登录失败");
		}
		wechatMeta.setSkey(Matchers.match("<skey>(\\S+)</skey>", res));
		wechatMeta.setWxsid(Matchers.match("<wxsid>(\\S+)</wxsid>", res));
		wechatMeta.setWxuin(Matchers.match("<wxuin>(\\S+)</wxuin>", res));
		wechatMeta.setPass_ticket(Matchers.match("<pass_ticket>(\\S+)</pass_ticket>", res));

		JSONObject baseRequest = new JSONObject();
		baseRequest.put("Uin", wechatMeta.getWxuin());
		baseRequest.put("Sid", wechatMeta.getWxsid());
		baseRequest.put("Skey", wechatMeta.getSkey());
		baseRequest.put("DeviceID", wechatMeta.getDeviceId());
		wechatMeta.setBaseRequest(baseRequest);
		
		LOGGER.debug("skey [{}]", wechatMeta.getSkey());
		LOGGER.debug("wxsid [{}]", wechatMeta.getWxsid());
		LOGGER.debug("wxuin [{}]", wechatMeta.getWxuin());
		LOGGER.debug("pass_ticket [{}]", wechatMeta.getPass_ticket());
		File output = new File("temp.jpg");
		if(output.exists()){
			output.delete();
		}
		
		
	}
	
	public void init() throws WechatException {

		this.login();
		wechatService.wxInit(wechatMeta);
		wechatService.openStatusNotify(wechatMeta);
		wechatContact = wechatService.getContact(wechatMeta);
		// 监听消息
		wechatListener.start(wechatService, wechatMeta);
//		wechatService.webwxsendmsg(wechatMeta,"服务启动成功!",userMap.get("threequarters"));
		//映射备注名或昵称 到 uuid
		JSONArray jSONArrayContactList = wechatContact.getMemberList();
		for (int i = 0; i < jSONArrayContactList.size(); i++) {
			JSONObject obj = jSONArrayContactList.get(i).asJSONObject();
			String UserName = obj.getString("UserName");
			String NickName = obj.getString("NickName");
			String RemarkName = obj.getString("RemarkName");
			if (RemarkName != null && !"".equals(RemarkName)) {
				String uid= userNameMap.put(RemarkName, UserName);
				if (uid!=null){
					userNameMap.remove(RemarkName);
					System.out.println(RemarkName+":备注名重复");
				}
			} else {
				String uid=userNameMap.put(NickName, UserName);
				if (uid!=null){
					userNameMap.remove(NickName);
					System.out.println(NickName+":昵称重复");
				}
			}
		}
//		System.out.println(userNameMap.get("创业圈"));
//		for (String s : userNameMap.keySet()) {
//			System.out.println(s);
//		}


	}
	public void sendMsg(String content,String to) {
		wechatService.webwxsendmsg(wechatMeta, content,userNameMap.get(to));

	}

	public WechatContact getWechatContact() {
		return wechatContact;
	}

	private String getUserRemarkName(String id) {
		String name = "这个人物名字未知";
		for (int i = 0, len = wechatContact.getMemberList().size(); i < len; i++) {
			JSONObject member = wechatContact.getMemberList().get(i).asJSONObject();
			if (member.getString("UserName").equals(id)) {
				if (StringKit.isNotBlank(member.getString("RemarkName"))) {
					name = member.getString("RemarkName");
				} else {
					name = member.getString("NickName");
				}
				return name;
			}
		}
		return name;
	}
}